﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MessageSystem.Default.infrastructure
{
    class strategy
    {
        public strategy(UInt32 max_msg_size, UInt32 max_block_size, UInt32 block_size)
        {
            max_block_size_ = max_block_size;
            max_msg_size_ = max_msg_size;
            block_size_ = block_size;
        }

        public block alloc_block()
        {
            block ret = new block((int)block_size_);
            cur_block_size_ += block_size_;
            ++cur_block_count_;
            ++history_block_count_;
            return ret;
        }

        public bool free_block(block ptr_block)
        {
            if (cur_block_size_ > max_block_size_)
            {
                ptr_block.free();
                --cur_block_count_;
                cur_block_size_ -= block_size_;
                return false;
            }
            else
            {
                return true;
            }
        }

        public msg alloc_msg()
        {
            msg ret = new msg();
            cur_msg_size_ += 4;
            ++cur_msg_count_;
            ++history_msg_count_;
            return ret;
        }

        public bool free_msg(msg ptr_msg)
        {
            if (cur_msg_size_ > max_msg_size_)
            {
                --cur_msg_count_;
                cur_msg_size_ -= 4;
                return false;
            }
            else
            {
                return true;
            }
        }

        private UInt32 max_msg_size_;
        private UInt32 cur_msg_size_;
        private UInt32 cur_msg_count_;
        private UInt32 history_msg_count_;

        private UInt32 block_size_;
        private UInt32 max_block_size_;
        private UInt32 cur_block_size_;
        private UInt32 cur_block_count_;
        private UInt32 history_block_count_;
    }
}
